package online.chazi.netkit.messaging;

import online.chazi.netkit.exception.MessageConvertException;

import java.nio.ByteBuffer;

/**
 * 说明：作者很懒，什么都没留下
 * Created by 叉子同学 on 2020-04-24 11:03
 */
public class MessageDecoder {

    public static Message decode(byte[] bytes) throws MessageConvertException {
        return decode(ByteBuffer.wrap(bytes));
    }

    public static Message decode(ByteBuffer buffer) throws MessageConvertException {
        int sourceLen = buffer.arrayOffset() + buffer.limit();
        if (sourceLen < Message.HEADER_SIZE) {
            throw new MessageConvertException("Message header length error.");
        } else {
            int messageId = buffer.getInt();
            byte extension = buffer.get();
            int dataLen = buffer.getInt();
            if (sourceLen < dataLen + Message.HEADER_SIZE) {
                throw new MessageConvertException("Message data length error.");
            } else {
                byte[] bytes = null;
                if (dataLen > 0) {
                    bytes = new byte[dataLen];
                    buffer.get(bytes);
                }
                return new Message(messageId, extension, bytes);
            }
        }
    }

}
